<?php

/**
 * 特批发票仓库
 * @author yuzy 2015-5-7
 */

namespace common\repositories\myhtsq;

use common\repositories\BaseRepository;
use common\entities\myhtsq\SpecialApprovalInvoiceEntity;
use common\error\ErrorCode;
use common\repositories\common\MyscrmContractSyncDeleteDataRepository;
use common\support\PageParam;
use common\support\Helper;
use common\support\StringHelper;
use Exception;

class SpecialApprovalInvoiceRepository extends BaseRepository {

    /**
     * 构造方法
     * @param unknown $config (optional)
     */
    public function __construct($config = []) {
        parent::__construct($config);
    }

    /**
     * 特批发票列表
     * @param \common\support\PageParam $pageParam 分页参数
     * @param integer $areaId 区域id
     * @param string $fulfil
     * @param string $keyword 关键字
     * @return array
     */
    public static function getSpecialApprovalInvoiceList($pageParam, $areaId, $fulfil, $keyword) {
        $skip = $pageParam->getSkipByPageParam();
        $query = SpecialApprovalInvoiceEntity::find();
        $query->select("myscrm_special_approval_invoice.*,myscrm_contract_manage.area_id,myscrm_contract_manage.company_id,myscrm_invoice.invoice_company_id,"
                ."myscrm_invoice.customer_name,myscrm_invoice.invoice_date,myscrm_contract_manage.contract_code");

        //区域id
        if (!empty($areaId)) {
            $query->andWhere(['myscrm_contract_manage.area_id' => $areaId]);
        }

        // 是否兑现
        if (!empty($fulfil)) {
            if($fulfil == '1'){
                $query->andWhere('myscrm_special_approval_invoice.actual_fulfil_time is not null');
            }
            else{
                $query->andWhere('myscrm_special_approval_invoice.actual_fulfil_time is null');
            }
        }

        // 关键字过滤
        if (!empty($keyword)) {
            $query->andWhere(['or', ['like', 'myscrm_contract_manage.contract_code', $keyword], ['like', 'myscrm_special_approval_invoice.invoice_no', $keyword], ['like', 'myscrm_invoice.customer_name', $keyword]]);
        }

        $query->leftJoin('myscrm_invoice', 'myscrm_invoice.invoice_no = myscrm_special_approval_invoice.invoice_no')
            ->leftJoin('myscrm_contract_manage', 'myscrm_invoice.contract_id = myscrm_contract_manage.contract_id')
            ->offset($skip)
            ->limit($pageParam->pageSize)
            ->orderBy([$pageParam->sortBy => $pageParam->sortAsc]);

        $result = $query->asArray()->all(); //这里必须asArray，否则无法获取关联字段的属性值

        //获取erp_user中信息
        if (!empty($result)) {
            foreach($result as $k=>$v){
                $result[$k]["principal_name"] = ErpUserRepository::getUserNameByBuguid($v["promise_fulfil_principle"]);
                $result[$k]["area_name"] = ErpBusinessUnitRepository::getBunameByBuguid($v["area_id"]);//合同签署区域
                $result[$k]["contract_company_name"] = ErpBusinessUnitRepository::getBunameByBuguid($v["company_id"]);//合同签署区域
                $result[$k]["invoice_company_name"] = ErpBusinessUnitRepository::getBunameByBuguid($v["invoice_company_id"]);//合同签署区域
            }
        }

        $totalResult = SpecialApprovalInvoiceEntity::find();
        if (!empty($areaId)) {
            $totalResult->andWhere(['myscrm_contract_manage.area_id' => $areaId]);
        }
        if (!empty($fulfil)) {
            if($fulfil == '1'){
                $totalResult->andWhere('myscrm_special_approval_invoice.actual_fulfil_time is not null');
            }else{
                $totalResult->andWhere('myscrm_special_approval_invoice.actual_fulfil_time is null');
            }
        }
        if (!empty($keyword)) {
            $totalResult->andWhere(['or', ['like', 'myscrm_contract_manage.contract_code', $keyword], ['like', 'myscrm_special_approval_invoice.invoice_no', $keyword], ['like', 'myscrm_invoice.customer_name', $keyword]]);
        }
        $totalResult->leftJoin('myscrm_invoice', 'myscrm_invoice.invoice_no = myscrm_special_approval_invoice.invoice_no')
                    ->leftJoin('myscrm_contract_manage', 'myscrm_invoice.contract_id = myscrm_contract_manage.contract_id');
        $total = $totalResult->count();

        $pageResult = Helper::setPageResult($total, $result);
        return $pageResult;
    }

    /**
     * 获取特批发票实体信息
     * @param string $invoiceId
     * @return \common\entities\myhtsq\SpecialApprovalInvoiceEntity
     */
    public static function getSpecialApprovalInvoiceInfo($invoiceId) {
        $model= SpecialApprovalInvoiceEntity::find()
            ->select('myscrm_special_approval_invoice.*')
            ->where(['special_approval_invoice_id'=>$invoiceId])
            ->asArray()
            ->one();
        if(!empty($model)){
            $model["principal_name"] = ErpUserRepository::getUserNameByBuguid($model["promise_fulfil_principle"]);
        }
        return $model;
    }

    /**
     * 新增特批发票
     * @param \common\models\myhtsq\SpecialApprovalInvoiceModel $invoiceModel
     * @return boolean|string 失败返回false，成功返回新增的特批发票Id
     */
    public function addSpecialApprovalInvoice($invoiceModel) {
        try {
            $entity = new SpecialApprovalInvoiceEntity();
            $entity->setAttributes($invoiceModel->attributes);
            $entity->special_approval_invoice_id = StringHelper::uuid();
            $result = $entity->save();
            if ($result === FALSE) {
//                $error = $entity->firstErrorMessage;
                return $this->setAndReturn(ErrorCode::ERR_SPECIAL_APPROVAL_INVOICE_SAVE_FAIL);
            } else {
                return $entity->primaryKey;
            }
        } catch (Exception $ex) {
            return $this->setAndReturn(ErrorCode::ERR_SPECIAL_APPROVAL_INVOICE_SAVE_FAIL, (string) $ex);
        }
    }

    /**
     * 更新特批发票
     * @param \common\models\myhtsq\SpecialApprovalInvoiceModel $invoiceModel
     * @return boolean|string 失败返回false，成功返回编辑的特批发票Id
     */
    public function updateSpecialApprovalInvoice($invoiceModel) {
        try {
            $entity = SpecialApprovalInvoiceRepository::getSpecialApprovalInvoiceById($invoiceModel->special_approval_invoice_id);
            if (is_null($entity)) {
                return $this->setAndReturn(ErrorCode::ERR_SPECIAL_APPROVAL_INVOICE_SAVE_FAIL);
            }
            $entity->setAttributes($invoiceModel->toArray());
            $result = $entity->update();
            if ($result === FALSE) {
//                $error = $entity->firstErrorMessage;
                return $this->setAndReturn(ErrorCode::ERR_SPECIAL_APPROVAL_INVOICE_SAVE_FAIL);
            } else {
                return $entity->special_approval_invoice_id;
            }
        } catch (\Exception $ex) {
            return $this->setAndReturn(ErrorCode::ERR_SPECIAL_APPROVAL_INVOICE_SAVE_FAIL, (string) $ex);
        }
    }

    /**
     * 根据Id获取特批发票
     * @param string $invoiceId
     * @return \common\entities\myhtsq\SpecialApprovalInvoiceEntity
     */
    public static function getSpecialApprovalInvoiceById($invoiceId) {
        return SpecialApprovalInvoiceEntity::findOne(['special_approval_invoice_id' => $invoiceId]);
    }

    /**
     * 根据发票编号获取特批发票
     * @param string $invoiceNumber
     * @return \common\entities\myhtsq\SpecialApprovalInvoiceEntity
     */
    public static function getSpecialApprovalInvoiceByInvoiceNumber($invoiceNumber) {
        return SpecialApprovalInvoiceEntity::findOne(['invoice_no' => $invoiceNumber]);
    }

    /**
     * 根据发票编号删除特批发票
     * @param string $invoiceNumber
     * @return 失败的返回false，成功则返回删除的记录条数
     */
    public function delSpecialApprovalInvoiceByInvoiceNumber($invoiceNumber){
        try {
            /** @var MyscrmContractSyncDeleteDataRepository $contractSyncDeleteDataRepository */
            $contractSyncDeleteDataRepository = \Yii::createObject(MyscrmContractSyncDeleteDataRepository::className());

            $deleteData = SpecialApprovalInvoiceEntity::findAll(['invoice_no' => $invoiceNumber]);

            $deleteResult = SpecialApprovalInvoiceEntity::deleteAll(['invoice_no' => $invoiceNumber]);

            if ($deleteResult > 0) {
                foreach ($deleteData as $data) {
                    $contractSyncDeleteDataRepository->add('myscrm_special_approval_invoice', 'special_approval_invoice_id', $data['special_approval_invoice_id']);
                }
            }

            return $deleteResult;

        } catch (\Exception $ex) {
            return $this->setAndReturn(ErrorCode::ERR_SPECIAL_APPROVAL_INVOICE_DELETE_FAIL, (string) $ex);
        }
    }

    /**
     * 根据特此发票id删除特批发票
     * @param type $invoiceId
     */
    public function delSpecialApprovalInvoice($invoiceId)
    {
        try {
            /** @var MyscrmContractSyncDeleteDataRepository $contractSyncDeleteDataRepository */
            $contractSyncDeleteDataRepository = \Yii::createObject(MyscrmContractSyncDeleteDataRepository::className());

            $deleteResult = SpecialApprovalInvoiceEntity::deleteAll(['special_approval_invoice_id' => $invoiceId]);

            if ($deleteResult > 0) {
                $contractSyncDeleteDataRepository->add('myscrm_special_approval_invoice', 'special_approval_invoice_id', $invoiceId);
            }

            return $deleteResult;
        } catch (\Exception $ex) {
            return $this->setAndReturn(ErrorCode::ERR_SPECIAL_APPROVAL_INVOICE_DELETE_FAIL, (string)$ex);
        }
    }
}
